import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import { reduxForm } from 'redux-form';
import { createPost } from '../actions/index';

class PostsNew extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit(props) {
    const promise = this.props.createPost(props);
    promise.then((res) => {
      // blog post has been created, navigate the user to the index
      // We navigate by calling this.context.router.push with the
      // new path to navigate to.
      this.context.router.push('/');
    })
  }
  render() {
    const { fields: { title, categories, content }, handleSubmit } = this.props;
    return (
      <div>
        <form onSubmit={ handleSubmit(this.onSubmit) }>
          <h2>Create A New Post</h2>

          <div className={ `form-group ${title.touched && title.invalid ? 'has-danger' : ''}`}>
            <label>Title</label>
            <input type="text" className="form-control" {...title} />
            <div className="text-help">
              { title.touched ? title.error : ''}
            </div>
          </div>

          <div className={ `form-group ${categories.touched && categories.invalid ? 'has-danger' : ''}`}>
            <label>Categories</label>
            <input type="text" className="form-control" {...categories } />
            <div className="text-help">
              { categories.touched ? categories.error : ''}
            </div>
          </div>

          <div className={ `form-group ${content.touched && content.invalid ? 'has-danger' : ''}`}>
            <label>Content</label>
            <textarea className="form-control" rows={10} {...content }/>
            <div className="text-help">
              { content.touched ? content.error : ''}
            </div>
          </div>

          <div>
            <button type="submit" className="btn btn-primary">
              保存
            </button>
            <Link to="/" className="btn btn-danger">
              返回
            </Link>
          </div>

        </form>
      </div>
    );
  }
}

function validate(values) {
  const errors = {};

  if(!values.title) {
    errors.title = 'Enter a username';
  }

  if(!values.categories) {
    errors.categories = 'Enter categories';
  }

  if(!values.content) {
    errors.content = 'Enter some content.';
  }

  return errors;
}

// connect: first argument is mapStatetToProps, 2nd is mapDispatchToProps
// reduxForm: 1st is form configuration, 2nd is mapStatetToProps, 3rd is
// mapDispatchToProps
export default reduxForm({
  form: 'PostsNewForm',
  fields: ['title', 'categories', 'content'],
  validate
}, null, {
  createPost
})(PostsNew);
